package cn.tedu.knows.portal.controller;


import cn.tedu.knows.portal.model.Question;
import cn.tedu.knows.portal.service.IQuestionService;
import cn.tedu.knows.portal.vo.QuestionVO;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author tedu.cn
 * @since 2022-03-04
 */
@RestController
@RequestMapping("/v1/questions")
@Slf4j
public class QuestionController {
    @Autowired
    private IQuestionService questionService;

    @GetMapping("/my")
    public PageInfo<Question> my(@AuthenticationPrincipal UserDetails user, Integer pageNum) {
        Integer pageSize = 8;
        if (pageNum == null) {
            pageNum = 1;
        }
        PageInfo<Question> pageInfo = questionService.getMyQuestions(user.getUsername(), pageNum, pageSize);
        return pageInfo;
    }

    @PostMapping("")
    public String createQuestion(@Validated QuestionVO questionVO,
                                 BindingResult result,
                                 @AuthenticationPrincipal UserDetails user) {
        log.debug("接收到的表单信息:{}", questionVO);
        if (result.hasErrors()) {
            String msg = result.getFieldError().getDefaultMessage();
            return msg;
        }
        questionService.saveQuestion(questionVO, user.getUsername());
        return "ok";
    }

    @GetMapping("/teacher")
    @PreAuthorize("hasRole('ROLE_TEACHER')")
    public PageInfo<Question> teacher(@AuthenticationPrincipal UserDetails user, Integer pageNum){
        Integer pageSIze=8;
        if (pageNum==null){
            pageNum=1;
        }
        PageInfo<Question> pageInfo=questionService.getTeacherQuestions(user.getUsername(),pageNum,pageSIze);
        return pageInfo;

    }

    @GetMapping("/{id}")
    public Question question(@PathVariable Integer id){
        Question question=questionService.getQuestionById(id);
        return question;
    }

}
